package com.pvdnc.outguess;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

public class RWReference<T> {
    private final AtomicReference<T> mRef=new AtomicReference<>();

    public RWReference(){

    }

    public RWReference(@NonNull T obj){
        set(obj);
    }

    private final AtomicBoolean mWritable=new AtomicBoolean(true);

    public boolean writable(){
        return mWritable.get();
    }

    public void setWritable(boolean writable){
        mWritable.set(writable);
    }

    private final AtomicBoolean mReadable=new AtomicBoolean(true);

    public boolean readable(){
        return mReadable.get();
    }

    public void setReadable(boolean readable){
        mReadable.set(readable);
    }

    public void set(@Nullable T obj){
        if(!writable())
            throw new IllegalStateException("obj is not currently writable now");
        mRef.set(obj);
    }

    public T get(){
        if(!readable())
            throw new IllegalStateException("obj is not currently readable now");
        return mRef.get();
    }
}
